package tacocloud.data;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementCreatorFactory;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import tacocloud.dao.Ingredient;
import tacocloud.dao.Taco;

import java.sql.Timestamp;
import java.sql.Types;
import java.util.Arrays;
import java.util.Date;

public class JdbcTacoRepostory implements TacoRepository {

    private JdbcTemplate jdbc;

    public JdbcTacoRepostory(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    /**
     * 实现保存功能
     * @param taco
     * @return
     */
    @Override
    public Taco save(Taco taco) {
        long tacoId = saveTacoInfo(taco);
        taco.setId(tacoId);
        for (Ingredient ingredient : taco.getIngredients()) {
            saveIngredientToTaco(ingredient, tacoId);
        }

        return taco;
    }

    private long saveTacoInfo(Taco taco){
        taco.setCreateAt(new Date());
        PreparedStatementCreator psc=new PreparedStatementCreatorFactory(
                "INSERT INTO taco(NAME, CREATEDAT) VALUES (?,?)",
                Types.VARCHAR,Types.TIMESTAMP
        ).newPreparedStatementCreator(
                Arrays.asList(
                        taco.getName(),
                        new Timestamp(taco.getCreateAt().getTime())
                )
        );
        KeyHolder keyHolder=new GeneratedKeyHolder();
        jdbc.update(psc,keyHolder);

        return keyHolder.getKey().longValue();
    }

    private void saveIngredientToTaco(Ingredient ingredient,long tacoId){   // 修改同上
        jdbc.update(
                "INSERT INTO taco_ingredients(TACO, INGREDIENT) VALUES (?,?)",
                tacoId,ingredient
        );
    }

}
